﻿using System;

namespace winS.UnityEditor.UIElement
{
    public abstract class UndoableValueControl<T> : ValueControl<T>, IUndoable<T>
    {
        private Action<T, T> _onValueChange;

        event Action<T, T> IUndoable<T>.onValueChange { add { _onValueChange += value; } remove { _onValueChange -= value; } }

        internal UndoableValueControl(ElementFactory elementFactory) : base(elementFactory)
        {
        }

        protected virtual void OnRedo(T newValue)
        {
            SetValueWithoutNotify(newValue);
            OnValueChanged(newValue);
        }
        protected virtual void OnUndo(T oldValue)
        {
            SetValueWithoutNotify(oldValue);
            OnValueChanged(oldValue);
        }
        protected override void SetValue(T value)
        {
            SendUndoValueChangeEvent(this.value, value);
            base.SetValue(value);
        }
        protected void SendUndoValueChangeEvent(T oldValue, T newValue)
        {
            _onValueChange?.Invoke(oldValue, newValue);
        }

        void IUndoable<T>.Redo(T newValue)
        {
            OnRedo(newValue);
        }
        void IUndoable<T>.Undo(T oldValue)
        {
            OnUndo(oldValue);
        }
    }
}